package cn.edu.swu.miniwebsvr.core;

import cn.edu.swu.miniwebsvr.handler.DefaultHandler;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.IOException;

public class Router {

    public void route(Parameter request, OutputStream response) {
        Config config = Config.getInstance();

        // 添加详细的请求日志
        System.out.println("=== Routing Request ===");
        System.out.println("Method: " + request.getMethod());
        System.out.println("URL: " + request.getUrl());
        System.out.println("URL Params: " + request.getUrlParams().size());
        System.out.println("Headers: " + request.getHeaders().size());

        Handler handler = config.getHandler(request.getUrl());

        if (handler == null) {
            System.out.println("No exact handler found for: " + request.getUrl());
            // 如果没有匹配的路由，使用 DefaultHandler 处理
            handler = config.getHandler("/");
            System.out.println("Using default handler");
        } else {
            System.out.println("Found handler for: " + request.getUrl());
        }

        if (handler != null) {
            try {
                System.out.println("Executing handler: " + handler.getClass().getSimpleName());
                handler.handle(request, response);
                System.out.println("Handler executed successfully");
            } catch (Exception e) {
                System.err.println("Handler execution error: " + e.getMessage());
                e.printStackTrace();
                sendInternalServerError(response, e);
            }
        } else {
            System.err.println("Critical: No handler available, even DefaultHandler is missing");
            sendInternalServerError(response, new RuntimeException("No handler available"));
        }

        System.out.println("=== Request Completed ===\n");
    }

    /**
     * 发送500 Internal Server Error响应
     */
    private void sendInternalServerError(OutputStream response, Exception e) {
        try {
            PrintWriter writer = new PrintWriter(response);

            String errorMessage = "Server encountered an error: " +
                    (e.getMessage() != null ? e.getMessage() : "Unknown error");

            String htmlContent = buildErrorHtml(500, "Internal Server Error", errorMessage);
            byte[] contentBytes = htmlContent.getBytes("UTF-8");

            // 发送HTTP响应头
            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/html; charset=utf-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println();

            // 发送错误页面HTML
            writer.print(htmlContent);
            writer.flush();

            System.err.println("Sent 500 error response: " + errorMessage);

        } catch (Exception ex) {
            System.err.println("Failed to send error response: " + ex.getMessage());
            // 如果连错误页面都无法发送，只能放弃
        }
    }

    /**
     * 发送404 Not Found响应
     */
    private void sendNotFoundError(OutputStream response, String url) {
        try {
            PrintWriter writer = new PrintWriter(response);

            String message = "The requested resource <code>" + url + "</code> was not found on this server.";
            String htmlContent = buildErrorHtml(404, "Not Found", message);
            byte[] contentBytes = htmlContent.getBytes("UTF-8");

            writer.println("HTTP/1.1 404 Not Found");
            writer.println("Content-Type: text/html; charset=utf-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println();

            writer.print(htmlContent);
            writer.flush();

            System.out.println("Sent 404 error for: " + url);

        } catch (Exception e) {
            System.err.println("Failed to send 404 response: " + e.getMessage());
        }
    }

    /**
     * 构建错误页面HTML
     */
    private String buildErrorHtml(int statusCode, String statusText, String message) {
        StringBuilder html = new StringBuilder();

        html.append("<!DOCTYPE html>");
        html.append("<html lang=\"zh-CN\">");
        html.append("<head>");
        html.append("    <meta charset=\"UTF-8\">");
        html.append("    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
        html.append("    <title>").append(statusCode).append(" ").append(statusText).append("</title>");
        html.append("    <style>");
        html.append("        body {");
        html.append("            font-family: Arial, sans-serif;");
        html.append("            margin: 0;");
        html.append("            padding: 40px;");
        html.append("            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);");
        html.append("            min-height: 100vh;");
        html.append("            display: flex;");
        html.append("            align-items: center;");
        html.append("            justify-content: center;");
        html.append("        }");
        html.append("        .error-container {");
        html.append("            background: white;");
        html.append("            padding: 40px;");
        html.append("            border-radius: 15px;");
        html.append("            box-shadow: 0 10px 30px rgba(0,0,0,0.2);");
        html.append("            text-align: center;");
        html.append("            max-width: 500px;");
        html.append("            width: 100%;");
        html.append("        }");
        html.append("        .error-title {");
        html.append("            color: #d32f2f;");
        html.append("            margin-bottom: 20px;");
        html.append("            font-size: 2em;");
        html.append("        }");
        html.append("        .error-code {");
        html.append("            background: #d32f2f;");
        html.append("            color: white;");
        html.append("            padding: 5px 10px;");
        html.append("            border-radius: 4px;");
        html.append("            font-weight: bold;");
        html.append("        }");
        html.append("        .error-message {");
        html.append("            margin: 20px 0;");
        html.append("            padding: 15px;");
        html.append("            background: #fff3e0;");
        html.append("            border-left: 4px solid #ff9800;");
        html.append("            text-align: left;");
        html.append("        }");
        html.append("        .home-link {");
        html.append("            display: inline-block;");
        html.append("            margin-top: 20px;");
        html.append("            padding: 12px 24px;");
        html.append("            background: #2196f3;");
        html.append("            color: white;");
        html.append("            text-decoration: none;");
        html.append("            border-radius: 6px;");
        html.append("            transition: background 0.3s;");
        html.append("        }");
        html.append("        .home-link:hover {");
        html.append("            background: #1976d2;");
        html.append("        }");
        html.append("    </style>");
        html.append("</head>");
        html.append("<body>");
        html.append("    <div class=\"error-container\">");
        html.append("        <h1 class=\"error-title\">").append(statusCode).append(" ").append(statusText).append("</h1>");
        html.append("        <div class=\"error-message\">");
        html.append("            ").append(message);
        html.append("        </div>");
        html.append("        <p>Please check the URL or return to the <a href=\"/\" class=\"home-link\">Home Page</a>.</p>");
        html.append("    </div>");
        html.append("</body>");
        html.append("</html>");

        return html.toString();
    }
}